﻿namespace TelecoSystems.Web {
    using System.Security.Authentication;
    using System.ServiceModel.DomainServices.Hosting;
    using System.ServiceModel.DomainServices.Server;
    using System.ServiceModel.DomainServices.Server.ApplicationServices;
    using System.Threading;
    using System.Collections.Generic;
    using System.Web.Security;
    using System;
    using System.Linq;
    using System.Security.Principal;
    using System.Web.Profile;

    /// <summary>
    ///    RIA Services DomainService responsible for authenticating users when
    ///    they try to log on to the application.
    ///    
    ///    Most of the functionality is already provided by the base class
    ///    AuthenticationBase
    /// </summary>
    /// 
    [EnableClientAccess]
    public class AuthenticationService : AuthenticationBase<User> {
        public User GetUserByGuid(Guid userId) {
            return CastToUser(Membership.GetUser(userId));
        }

        [RequiresRole("Administrator")]
        public IQueryable<User> GetAllUsers() {
            return Membership.GetAllUsers().Cast<MembershipUser>().Select(mu => CastToUser(mu)).AsQueryable();
        }

        [Update(UsingCustomMethod=true)]
        public void UpdateTheUser(User user) {
            UpdateUserCore(user);
        }

        protected override void UpdateUserCore(User user) {
            MembershipUser mUser = CastToMembershipUser(user);

            ProfileBase mProfile = ProfileBase.Create(mUser.UserName);
            mProfile.SetPropertyValue("Email", user.Email);
            mProfile.SetPropertyValue("FriendlyName", user.FriendlyName);
            mProfile.SetPropertyValue("Phone", user.Phone);
            mProfile.Save();

            Membership.UpdateUser(mUser);
        }

        [Update(UsingCustomMethod=true)]
        public void ChangePassword(User user, string oldPassword, string newPassword) {
            MembershipUser mUser = Membership.GetUser(user.Name);
            mUser.ChangePassword(oldPassword, newPassword);
        }

        private User CastToUser(MembershipUser membershipUser) {
            return this.GetAuthenticatedUser(
                new GenericPrincipal(new GenericIdentity(membershipUser.UserName), new string[0]));
        }

        private MembershipUser CastToMembershipUser(User user) {
            return Membership.GetUser(user.Name);
        }
    }
}
